package com.com.datastructures.queue;

import java.util.ArrayDeque;

/**
 * Created with IntelliJ IDEA.
 * User: Ngo Lap Thanh
 * Date: 16/06/14
 * Time: 9:54 AM
 * To change this template use File | Settings | File Templates.
 */
public class BlockingQueueUsingGB<T> implements Queue<T> {

    ArrayDeque<T> q = new ArrayDeque<>();

    @Override
    public void add(T t) {
        synchronized (q){
            q.add(t);
            System.out.println("\nConsumer added in the queue : "
                    + t
                    + " At time "
                    + System.nanoTime()
            );
            q.notifyAll();
        }
    }

    @Override
    public T poll() {
        T t = null;
        synchronized (q) {
            while (q.isEmpty()) {
                try {
                    q.wait();
                } catch (InterruptedException e) {
                    // don't swallow it.
                }
            }
            t = q.poll();
            System.out.println("Thread : " +
                    Thread.currentThread().getName() +
                    " polled : "+ t + " At time : "+ System.nanoTime()
            );
        }


        return t;
    }
}
